﻿using AutoMapper;

using MediatR;
using TraceabilityApp_Api.Application.Command.Traceability;
using TraceabilityApp_Domain;
using TraceabilityApp_ErrorCode;
using TraceabilityApp_Infrastructure;

namespace TraceabilityApp_Api.Application.Handler.Traceability
{
    public class AddTraceadilityHandler : IRequestHandler<AddTraceadilityCommand, ApiResult<int>>
    {
        private readonly IBase<TraceabilityModel> tracebilityRepo;
        private readonly IMapper mapper;

        public AddTraceadilityHandler(IBase<TraceabilityModel> tracebilityRepo,IMapper mapper)
        {
            this.tracebilityRepo = tracebilityRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddTraceadilityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var tracebility = mapper.Map<TraceabilityModel>(request);
            
            var r=tracebilityRepo.Add(tracebility).Result;
            if(r>0)
            {
                result.Code = ApiEnum.OK;
                result.Msg = "溯源基本信息添加成功";
                result.Data= r;
                return Task.FromResult(result);
            }
            else
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "溯源基本信息添加失败";
                result.Data = r;
                return Task.FromResult(result);
            }
        }
    }
}
